/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AfMessageService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SharedModule } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';

import { ExcelQueueService } from './excel-queue.service';
import { AfSystemService } from '../../af-system.service';

@Component({
  selector: 'app-excel-queue',
  standalone: true,
  imports: [SharedModule],
  templateUrl: './excel-queue.component.html'
})
export class ExcelQueueComponent implements OnInit {
  queryParams: any = { queueId: '', fileName: '', business: '' };
  req: any = { params: this.queryParams, lazyLoad: true };
  isLoading = false;
  url: any;

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    // { title: '编号', index: 'id', sort: true },
    { title: '文件名称', index: 'fileName' },
    { title: '业务类型', index: 'title' },
    { title: '总行数', type: 'number', index: 'totalCount', className: 'text-center' },
    { title: '成功数', type: 'number', index: 'successCount', className: 'text-center' },
    { title: '更新人', index: 'lastModifiedBy' },
    { title: '更新时间', type: 'date', index: 'lastModifiedDate' },
    {
      title: '状态',
      type: 'tag',
      index: 'syncCode',
      tag: {
        0: { text: '上传成功', color: 'blue' },
        1: { text: '数据导入', color: 'orange' },
        2: { text: '导入成功', color: 'success' },
        3: { text: '导入失败', color: 'red' }
      }
    },
    {
      title: '操作',
      buttons: [
        {
          text: '下载文件',
          icon: 'download',
          tooltip: `下载原始文件`,
          click: (record, _modal) => {
            this.downloadFile(record);
          }
        },
        { text: '查看日志', icon: 'eye', click: (item: any) => this.viewLog(item) },
        {
          text: '删除',
          icon: 'delete',
          type: 'del',
          tooltip: `删除此记录`,
          pop: {
            title: '您确定要删除此记录吗？',
            okType: 'danger',
            icon: 'star'
          },
          click: (record, _modal) => {
            this.delete(record);
          }
        }
      ]
    }
  ];

  constructor(
    private route: ActivatedRoute,
    private cdr: ChangeDetectorRef,
    private msg: AfMessageService,
    private excelService: ExcelQueueService,
    private modal: ModalHelper,
    private router: Router,
    private modalForm: NzModalService,
    private sysSrv: AfSystemService
  ) {
    this.url = this.excelService.getQueryUrl();

    const params = this.route.snapshot.queryParams;
    if (params['queueId']) {
      this.queryParams.queueId = params['queueId'];
    }
    if (params['business']) {
      this.queryParams.business = params['business'];
    }
    console.log(this.queryParams);

    this.req = { params: this.queryParams, lazyLoad: false };
  }

  ngOnInit() {
    this.queryFileType();

    setTimeout(() => {
      this.isLoading = false;
      this.st.reset(this.queryParams);
      this.cdr.detectChanges();
    }, 200);
  }

  updateFileTypes: any[] = [];
  queryFileType() {
    this.sysSrv.queryFileType().subscribe(body => {
      // console.log(JSON.stringify(body));
      if (body.status) {
        this.updateFileTypes = [];
        this.updateFileTypes = body.data;
      } else {
        this.msg.msg_warning('加载上传文件类型报错');
      }
    });
  }

  public query() {
    if (!this.queryParams.fileName) {
      this.queryParams.fileName = '';
    }
    if (!this.queryParams.business) {
      this.queryParams.business = '';
    }
    console.log(this.queryParams);
    this.st.reset(this.queryParams);
  }

  delete(item: any) {
    try {
      this.excelService.delete(item.id).subscribe(body => {
        if (body.status) {
          this.msg.notice_success('历史记录', `${item.fileName} 记录删除成功`);
          this.query();
        } else {
          this.msg.notice_warning('历史记录', `${item.fileName} 删除失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  viewLog(record: any = {}) {
    this.router.navigateByUrl(`/system/excel/queue/log?queueId=${record.id}`);
  }

  downloadFile(record: any = {}) {
    this.cdr.detectChanges();
    try {
      const url = this.excelService.downloadFile(record.id);
    } finally {
      this.cdr.detectChanges();
    }
  }

  // 查看当然记录 -- 用于开发测试
  viewJson(record: any = {}) {
    // this.codegen.viewJson(record);
  }
}
